package service

import (
    "errors"
    "generator-tool/models"
    "generator-tool/repository"
)

type ShGoodsCategoryService struct {
    Repo *repository.ShGoodsCategoryRepository
}

func NewShGoodsCategoryService(repo *repository.ShGoodsCategoryRepository) *ShGoodsCategoryService {
    return &ShGoodsCategoryService{Repo: repo}
}

func (s *ShGoodsCategoryService) CreateShGoodsCategory(ShGoodsCategory *models.ShGoodsCategory) error {
    return s.Repo.CreateShGoodsCategory(ShGoodsCategory)
}

func (s *ShGoodsCategoryService) GetAllShGoodsCategorys() ([]models.ShGoodsCategory, error) {
    return s.Repo.GetAllShGoodsCategorys()
}

func (s *ShGoodsCategoryService) GetShGoodsCategoryByID(id uint) (*models.ShGoodsCategory, error) {
    if id == 0 {
        return nil, errors.New("invalid id")
    }
    return s.Repo.GetShGoodsCategoryByID(id)
}

func (s *ShGoodsCategoryService) UpdateShGoodsCategory(id uint, ShGoodsCategory *models.ShGoodsCategory) error {
    existing, err := s.Repo.GetShGoodsCategoryByID(id)
    if err != nil {
        return errors.New("record not found")
    }

    // Copy fields (skip primary key)
    existing.ParentId = ShGoodsCategory.ParentId
    existing.Name = ShGoodsCategory.Name
    existing.Sort = ShGoodsCategory.Sort
    existing.IsShow = ShGoodsCategory.IsShow
    existing.CreateTime = ShGoodsCategory.CreateTime
    existing.UpdateTime = ShGoodsCategory.UpdateTime

    return s.Repo.UpdateShGoodsCategory(existing)
}

func (s *ShGoodsCategoryService) DeleteShGoodsCategory(id uint) error {
    _, err := s.Repo.GetShGoodsCategoryByID(id)
    if err != nil {
        return errors.New("record not found")
    }
    return s.Repo.DeleteShGoodsCategory(id)
}